package com.business.commons.baseUtil;


/**
 * 
     * ClassName: FormatJSONStr <br/> 
     * Function: 专门用来解析json字符串的 <br/> 
     * Reason: TODO ADD REASON(可选). <br/> 
     * date: 2015年3月16日 上午10:50:22 <br/> 
     * 
     * @author ddr 
     * @version  
     * @since JDK 1.6
 */
public class FormatJSONStr {
 
  public static void main(String[] args) {
	  
	  String jsonStr = "{\"result\":\"1\",\"peson\":{\"nsd\":\"dai\",age:15,\"pad\":{\"aaa\":12,\"ag\":\"fds\"}},\"errorMsg\":null,\"errorCode\":null,\"sign\":\"f827eb61bfd5beeaa371bb5228fcad45\",\"language\":\"zhcn\",\"sessionId\":\"oaapp_36_98\",\"userId\":36,\"loginName\":\"drdai\",\"realname\":\"戴德荣\",\"gender\":0,\"corpId\":100000001,\"deptId\":0,\"nameFirstChar\":\"D\",\"regDate\":\"2014-03-20 17:12:14\",\"lastTime\":\"2015-03-16 10:37:43\",\"loginTime\":\"2015-03-16 10:43:57\"}";
	      String fotmatStr = FormatJSONStr.get().format(jsonStr);
//		fotmatStr = fotmatStr.replaceAll("\n", "<br/>");
//		fotmatStr = fotmatStr.replaceAll("\t", "    ");
    System.out.println(fotmatStr);
  } 
  
  private FormatJSONStr(){
		
	}
	
  public static FormatJSONStr get() {
		if(instance == null ){
			instance = new FormatJSONStr(); 
		}
		return instance;
	}
	
	private static FormatJSONStr instance;
  /**
   * 得到格式化json数据  退格用\t 换行用\r
   */
  public  String format(String jsonStr) {
    int level = 0;
    StringBuffer jsonForMatStr = new StringBuffer();
    for(int i=0;i<jsonStr.length();i++){
      char c = jsonStr.charAt(i);
      if(level>0&&'\n'==jsonForMatStr.charAt(jsonForMatStr.length()-1)){
        jsonForMatStr.append(getLevelStr(level));
      }
      switch (c) {
      case '{': 
      case '[':
        jsonForMatStr.append(c+"\n");
        level++;
        break;
      case ',': 
        jsonForMatStr.append(c+"\n");
        break;
      case '}':
      case ']':
        jsonForMatStr.append("\n");
        level--;
        jsonForMatStr.append(getLevelStr(level));
        jsonForMatStr.append(c);
        break;
      default:
        jsonForMatStr.append(c);
        break;
      }
    }
    
    return jsonForMatStr.toString();

  }
  
  private static String getLevelStr(int level){
    StringBuffer levelStr = new StringBuffer();
    for(int levelI = 0;levelI<level ; levelI++){
      levelStr.append("\t");
    }
    return levelStr.toString();
  }

}